package com.eshop.dao;

import com.eshop.domain.Category;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sergey on 17.12.13.
 */
public class CategoryDao extends HibernateUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(CategoryDao.class);

    public static final int ROOT_CATEGORY_ID = 0;

    public List<Category> load() {
        Session session = null;
        try {
            session = getSessionFactory().openSession();
            return session.createCriteria(Category.class).list();
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return null;
    }

    public List<Category> loadTree() {
        Session session = null;
        try {
            session = getSessionFactory().openSession();
            return session.createCriteria(Category.class)
                    .add(Restrictions.eq("parentId", ROOT_CATEGORY_ID)).list();
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return null;
    }

    public List<Category> loadLeafsOfParent(Category category) {
        ArrayList<Category> categories = new ArrayList<Category>();
        categories.add(category);

        for (Category ctg : category.getSubCategories()) {
            if (ctg.getSubCategories() == null || ctg.getSubCategories().isEmpty()) {
                categories.add(ctg);
            } else {
                categories.addAll(loadLeafsOfParent(ctg));
            }
        }
        return categories;
    }

    public List<Category> loadByParentId(int id) {
        Session session = null;
        try {
            session = getSessionFactory().openSession();
            return session.createCriteria(Category.class)
                    .add(Restrictions.eq("parentId", id)).list();
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return null;
    }
}
